﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameController : MonoBehaviour
{
	// Start is called before the first frame update
	public Transform GenerateBallLeftPos;
	public Transform GenerateBallRightPos;
	public int BallCount;
	public GameObject Platform;
	public GameObject[] BallPrefab;
	public List<GameObject> currentBalls;
	public float[] ScaleRange;
	bool BallDestroy = false;
	public float alphaChangeSpeed;
	public float GenerateRate = 0.1f;
	void Start()
	{
		StartCoroutine(StartGenerating());
	}

	// Update is called once per frame
	void Update()
	{

	}

	IEnumerator StartGenerating()
	{
		int currentBallCount = 0;
		while (currentBallCount < BallCount)
		{
			yield return new WaitForSeconds(GenerateRate);
			Vector2 temp = new Vector2(Random.Range(GenerateBallLeftPos.position.x, GenerateBallRightPos.position.x), GenerateBallRightPos.position.y);
			GameObject _ins = Instantiate(BallPrefab[Random.value >= 0.5 ? 0 : 1]);
			_ins.transform.position = new Vector3(temp.x, temp.y, 0);
			_ins.transform.localScale *= Random.Range(ScaleRange[0], ScaleRange[1]);
			_ins.gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(0, -5);
			currentBalls.Add(_ins);
			currentBallCount = currentBalls.Count;
		}
		yield return new WaitForSeconds(30f);
		BallDestroy = true;//开始执行销毁
		StartCoroutine(PlatFormDisappear());
	}

	IEnumerator PlatFormDisappear()
	{
		Platform.SetActive(false);
		yield return new WaitForSeconds(4f);
		while (true)
		{
			yield return new WaitForEndOfFrame();
			for (int i = 0; i < currentBalls.Count; i++)
			{
				if (currentBalls[i].GetComponent<SpriteRenderer>().color.a <= 0.1f)
				{
					StartCoroutine(currentBalls[i].GetComponent<BallDestroySelf>().DestroySelf());
					currentBalls.Remove(currentBalls[i]);
					continue;
				}
				float r = currentBalls[i].GetComponent<SpriteRenderer>().color.r;
				float g = currentBalls[i].GetComponent<SpriteRenderer>().color.g;
				float b = currentBalls[i].GetComponent<SpriteRenderer>().color.b;
				float a = currentBalls[i].GetComponent<SpriteRenderer>().color.a;
				currentBalls[i].GetComponent<SpriteRenderer>().color = new Color(r, g, b, a - Time.deltaTime * alphaChangeSpeed);
			}
			if (currentBalls.Count == 0)
			{
				break;
			}
		}
		BallDestroy = false;
		Platform.SetActive(true);
		StartCoroutine(StartGenerating());
	}
}
